/*
 * Copyright (c) 2020. André Mion
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.andremion.louvre.preview;


import com.andremion.louvre.CheckRadioView;
import com.andremion.louvre.ResourceTable;
import com.andremion.louvre.data.MediaLoader;
import com.andremion.louvre.loader.ResultSetLoader;
import com.andremion.louvre.util.Utils;
import com.andremion.louvre.util.transition.MediaSharedElementCallback;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.PageSlider;
import ohos.agp.window.dialog.ToastDialog;
import ohos.data.resultset.ResultSet;
import ohos.utils.Pair;
import ohos.utils.net.Uri;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import static com.andremion.louvre.Louvre.*;
import static com.andremion.louvre.StoragePermissionActivity.RESULT_OK;


public class PreviewActivity extends Ability implements MediaLoader.Callbacks, PreviewAdapter.Callbacks {
    private static final int NO_POSITION = -1;

    /**
     * Start the Gallery Activity with additional launch information.
     *
     * @param activity        Context to launch activity from.
     * @param requestCode     If >= 0, this code will be returned in onActivityResult() when the activity exits.
     * @param maxSelection    The max count of image selection
     * @param selection       The current image selection
     * @param mediaTypeFilter The media types that will display
     * @param mThemeColor     Color
     * @param bucketId        ID
     * @param checkView       View
     * @param images          IMages
     * @param imageView       ImageView
     * @param position        Position
     */
    public static void startActivity2(Ability activity, int requestCode, int mThemeColor, Component imageView,
                                      Component checkView, long bucketId, int position,
                                      List<Uri> selection, int maxSelection, List<Uri> images,
                                      String... mediaTypeFilter) {

        Intent intent = new Intent();
        intent.setParam(EXTRA_BUCKET_ID, bucketId);
        intent.setParam(EXTRA_POSITION, position);
        intent.setParam(EXTRA_SELECTION, new LinkedList<>(selection));
        intent.setParam(IMAGES, new LinkedList<>(images));
        intent.setParam(EXTRA_THEME_COLOR, mThemeColor);
        intent.setParam(EXTRA_MAX_SELECTION, maxSelection);
        intent.setParam(EXTRA_MEDIA_TYPE_FILTER, mediaTypeFilter);

        Operation operation = new Intent.OperationBuilder()
                .withBundleName(activity.getBundleName())
                .withAbilityName(PreviewActivity.class.getName())
                .build();
        intent.setOperation(operation);
        activity.startAbilityForResult(intent, requestCode);
    }


    @SafeVarargs
    private static Pair[] concatToSystemSharedElements(Ability activity, Pair<Component, String>... activitySharedElements) {

        List<Pair<Component, String>> sharedElements = new ArrayList<>();
        sharedElements.addAll(Arrays.asList(activitySharedElements));

        Pair[] result = new Pair[sharedElements.size()];
        sharedElements.toArray(result);
        return result;
    }

    public static int getPosition(int resultCode, Intent data) {
        if (resultCode == RESULT_OK && data != null && data.hasParameter(EXTRA_POSITION)) {
            return data.getIntParam(EXTRA_POSITION, NO_POSITION);
        }
        return NO_POSITION;
    }

    public static List<Uri> getSelection(Intent data) {
        return (List<Uri>) data.getSerializableParam(EXTRA_SELECTION);
    }

    private ResultSetLoader mMediaLoader;
    private PreviewAdapter mAdapter;
    private PageSlider mViewPager;
    private CheckRadioView radioCheck;
    private int mThemeColor;

    @Override
    public void onStart(Intent savedInstanceState) {
        super.onStart(savedInstanceState);
        super.setUIContent(ResourceTable.Layout_activity_preview);
        mThemeColor = getIntent().getIntParam(EXTRA_THEME_COLOR, 0);
        if (mThemeColor == 0) {
            getWindow().setStatusBarColor(Utils.getColor(getContext(), ResourceTable.Color_default_theme_color));
        } else {
            getWindow().setStatusBarColor(Utils.getColor(getContext(), mThemeColor));
        }
        MediaSharedElementCallback sharedElementCallback = new MediaSharedElementCallback();
        List<Uri> selection = (List<Uri>) getIntent().getSerializableParam(EXTRA_SELECTION);
        assert selection != null;
        int maxSelection = getIntent().getIntParam(EXTRA_MAX_SELECTION, 0);
        Image ivBack = (Image) findComponentById(ResourceTable.Id_imageMatisse_back);
        ivBack.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                onBackPressed();
            }
        });
        radioCheck = (CheckRadioView) findComponentById(ResourceTable.Id_radioCheck);
        radioCheck.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                mAdapter.selectCurrentItem(mViewPager.getCurrentPage());
            }
        });

        mAdapter = new PreviewAdapter(this, radioCheck, sharedElementCallback, selection);
        mAdapter.setCallbacks(this);
        mAdapter.setMaxSelection(maxSelection);
        mViewPager = (PageSlider) findComponentById(ResourceTable.Id_view_pager);
        mViewPager.setProvider(mAdapter);
        mViewPager.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int position, float value, int i1) {
            }

            @Override
            public void onPageSlideStateChanged(int position) {
            }

            @Override
            public void onPageChosen(int position) {
                onCheckedUpdated(mAdapter.isSelected(position));
            }
        });
        mMediaLoader = new ResultSetLoader(this);
        if (getIntent().hasParameter(EXTRA_MEDIA_TYPE_FILTER)) {
            mMediaLoader.setSelectionArgsForSingleMediaType(getIntent().getStringArrayParam(EXTRA_MEDIA_TYPE_FILTER));
        }
        onAlbumSelected();
    }

    private void onAlbumSelected() {
        List<Uri> mImages = (List<Uri>) getIntent().getSerializableParam(IMAGES);
        swapData(mImages);
    }

    @Override
    protected void onInactive() {
        super.onInactive();
    }

    @Override
    protected void onBackPressed() {
        Intent mIntent = new Intent();
        mIntent.setParam(EXTRA_SELECTION, new LinkedList<>(mAdapter.getSelection()));
        setResult(RESULT_OK, mIntent);
        super.onBackPressed();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * onBucketLoadFinished
     */
    public void onBucketLoadFinished(ResultSet data) {
    }

    /**
     * onMediaLoadFinished
     */
    public void onMediaLoadFinished(ResultSet data) {
        swapData((List<Uri>) getIntent().getSerializableParam(IMAGES));
    }

    @Override
    public void onCheckedUpdated(boolean checked) {
        radioCheck.setChecked(checked);
    }

    @Override
    public void onMaxSelectionReached() {
        new ToastDialog(getContext()).setText(Utils.getString(getContext(),
                ResourceTable.String_activity_gallery_will_exceed_max_selection)).show();
    }

    /**
     * finishAfterTransition
     */
    public void finishAfterTransition() {
        setResult();
    }

    /**
     * onDestroy
     */
    protected void onDestroy() {
        mMediaLoader.cancel(true);
    }

    private void swapData(List<Uri> mImages) {
        int position = getIntent().getIntParam(EXTRA_POSITION, 0);
        mAdapter.swapData(mImages);
        mAdapter.setInitialPosition(position);
        mViewPager.setCurrentPage(position, false);
        setCheckboxTransitionName(position);
    }

    private void setResult() {
        int position = mViewPager.getCurrentPage();
        Intent data = new Intent();
        data.setParam(EXTRA_POSITION, position);
        data.setParam(EXTRA_SELECTION, new LinkedList<>(mAdapter.getSelection()));
        setResult(RESULT_OK, data);
        setCheckboxTransitionName(position);
    }

    private void setCheckboxTransitionName(int position) {
    }
}